# Create your views here.
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from room_booking.Booking.models import *
from django.views.decorators.csrf import *
#first page
def main_page(request): # function for login User or Admin
     return render_to_response('mainpage.html',)

class ComputerNumber: #get numberComputer,date,time
     def __init__(self):
         self.number=0
         self.date=""
         self.time=""
     def inputNumber(self,num): #set number Computer
         self.number=num
     def number(self):  #return number Computer
         return self.number
     def inputDate(self,date):  #set date
          self.date=date
     def date(self):  #return date
         return self.date
     def inputTime(self,time):  #set time
         self.time=time
     def time(self):  #return time
         return self.time 
value = ComputerNumber()  #create object

user_ID = ""

def set_UserID(u_ID):  #set user ID
    global user_ID
    user_ID = u_ID

def get_UserID():  #get user ID
    return user_ID
    
@csrf_exempt
def inputs_booking(request):
     if "userID" in request.session:
         computer = Computer.objects.all()  #keep object computer 
         errors = []# keep error
         if request.method == 'POST': 
             if not request.POST['sid']:  #check error when not input ID
                 errors.append("Please Enter Computer ID.")
             if not request.POST['date']:  #check error when not input date
                 errors.append("Please Enter Date.")
             else:
                  com_id = request.POST['sid']  #keep computer id  
                  date = request.POST['date'] #keep computer date 
                  com=Computer.objects.get(Computer_ID=com_id) #get computer id from Computer model
                  #check input computer id and date if havn't date and computer id So new create
                  if Booking.objects.filter(computer=com_id).filter(Date=date).count()==0:   
                      bookings=Booking.objects.create(computer=com,Date=date)
                      Status = "had not booking"
                      #create status time
                      Timing.objects.create(booking=bookings,Time9_10=Status,Time10_11=Status,Time11_12=Status,Time12_13=Status,
                       Time13_14=Status,Time14_15=Status,Time15_16=Status,Time16_17=Status,Time17_18=Status,Time18_19=Status)  
                  value.inputNumber(com_id)
                  value.inputDate(date)
                  return HttpResponseRedirect('/booking_times')
         return render_to_response('booking.html', locals())
     else:
          return HttpResponseRedirect('/')

def update_booking(com,symbol):
    freq=0
    computer=Computer.objects.filter(Computer_ID=com).all() #get computer id for recieve frequency
    for com_id in computer:
          freq = com_id.Frequency
    #add frequency when booking succes 
    if symbol == 1:
         freq = freq + 1
    #minus frequency when delete booking  
    elif symbol == 2:
         freq = freq - 1
    Computer.objects.filter(Computer_ID=com).update(Frequency=freq)

@csrf_exempt
def booking_times(request):
    com = value.number
    date = value.date
    errors = ""
    #show time all so can booking
    time_all = show_select()
    show_date = Booking.objects.get(computer=com,Date=date)  #get date and number computer for search time booking
    show_time = Timing.objects.filter(booking=show_date).all()
    if request.method == 'POST':
        if not request.POST['time']:
            errors = "Please Enter Time."
        else:
            times=request.POST['time']
            update_status_time(times,"had booking")
            value.inputTime(times)
            res = Register.objects.get(Person_ID=get_UserID())
            comp=Computer.objects.get(Computer_ID=str(com))
            #keep id,number computer,date,time in database
            Booking_history.objects.create(register=res,computer=comp,Date=date,Time=times)  
            update_booking(com,1)  #update status time  
            return HttpResponseRedirect('/booking_success')
    return render_to_response('booking_times.html', locals())

def show_select():
    Status = "had not booking"
    com = value.number
    date = value.date
    time =[]
    date = Booking.objects.get(computer=com,Date=date)  #get number computer and date from Booking
    #check time (had not booking)
    if Timing.objects.filter(booking=date).filter(Time9_10=Status).count():
        time.append('9.00-10.00')
    if Timing.objects.filter(booking=date).filter(Time10_11=Status).count():
        time.append('10.00-11.00')
    if Timing.objects.filter(booking=date).filter(Time11_12=Status).count():
        time.append('11.00-12.00')
    if Timing.objects.filter(booking=date).filter(Time12_13=Status).count():
        time.append('12.00-13.00')
    if Timing.objects.filter(booking=date).filter(Time13_14=Status).count():
        time.append('13.00-14.00')
    if Timing.objects.filter(booking=date).filter(Time14_15=Status).count():
        time.append('14.00-15.00')
    if Timing.objects.filter(booking=date).filter(Time15_16=Status).count():
        time.append('15.00-16.00')
    if Timing.objects.filter(booking=date).filter(Time16_17=Status).count():
        time.append('16.00-17.00')
    if Timing.objects.filter(booking=date).filter(Time17_18=Status).count():
        time.append('17.00-18.00')
    if Timing.objects.filter(booking=date).filter(Time18_19=Status).count():
        time.append('18.00-19.00')
    return time
        
def update_status_time(times,st): 
    Status = st
    com = value.number
    date = value.date
    date = Booking.objects.get(computer=com,Date=date)  #get number computer and date from Booking 
    #check input time and update status 
    if times == "9.00-10.00":
        Timing.objects.filter(booking=date).update(Time9_10=Status)
    elif times == "10.00-11.00":
        Timing.objects.filter(booking=date).update(Time10_11=Status)
    elif times == "11.00-12.00":
        Timing.objects.filter(booking=date).update(Time11_12=Status)
    elif times == "12.00-13.00":
        Timing.objects.filter(booking=date).update(Time12_13=Status)
    elif times == "13.00-14.00":
        Timing.objects.filter(booking=date).update(Time13_14=Status)
    elif times == "14.00-15.00":
        Timing.objects.filter(booking=date).update(Time14_15=Status)
    elif times == "15.00-16.00":
        Timing.objects.filter(booking=date).update(Time15_16=Status)
    elif times == "16.00-17.00":
        Timing.objects.filter(booking=date).update(Time16_17=Status)
    elif times == "17.00-18.00":
        Timing.objects.filter(booking=date).update(Time17_18=Status)
    elif times == "18.00-19.00":
        Timing.objects.filter(booking=date).update(Time18_19=Status)


def booking_success(request):
     if "userID" in request.session:
          #get value from object and show when booking success
          com = value.number
          date = value.date
          time = value.time
          return render_to_response('booking_success.html', locals())
     else:
          return HttpResponseRedirect('/')

@csrf_exempt
def booking_history(request):
     if "userID" in request.session:
          com_id = Register.objects.get(Person_ID=get_UserID())
          computer = Booking_history.objects.filter(register=com_id).all()  #check computer id(Person_ID)
          if request.method == 'POST': 
               date = request.POST['com_date']
               time = request.POST['com_time']
               com = request.POST['com_computer']
               #keep Person_ID for delete
               com_id_delete = Register.objects.get(Person_ID=request.POST['com_register'])
               #keep computer,time and date for delete
               Booking_history.objects.filter(register=com_id_delete).filter(computer=
                com).filter(Time=time).filter(Date=date).delete()
               value.inputNumber(com)
               value.inputDate(date)
               update_status_time(time,"had not booking")#update status time
               update_booking(com,2)
               
          return render_to_response('booking_history.html', locals())
     else:
          return HttpResponseRedirect('/')

@csrf_exempt    
def home_page(request):
    if request.POST:
        errors = ""
        state = 0
        # reseive id and password from block in template
        u_id = request.POST['u_id']
        u_pass = request.POST['u_pass']
        
        request.session["userID"] = u_id  # set user ID
        request.session["userPass"] = u_pass # set user password
        userID = request.session["userID"]
        # call all information in Register base
        user_reg = Register.objects.all()
        ''' password validated
            if password is not correct send errors
            then show it on web browser
        '''  
        for i in user_reg:
            if(i.Person_ID == u_id and i.Password == u_pass):
                state = 1
                Name = i.Name
                SirName = i.SirName
                set_UserID(i.Person_ID)
                break
            elif(i.Person_ID == u_id and i.Password != u_pass):
                state = 2
                errors = "YOUR USERNAME OR PASSWORD IS INVALID."
                break
            elif(i.Person_ID != u_id):
                state = 3
                errors = "YOUR USERNAME OR PASSWORD IS INVALID."
        if state == 1:
            return render_to_response('login_success.html',locals())
        else:
            return render_to_response('login_page.html',locals())
    else :
        return render_to_response('login_page.html',locals())

@csrf_exempt
def user_register(request):
    #report to user for fill all blanket
    errors = ""
    blankets = ""
    #  for choose in combobox in template
    depart_list = ["ME","Cpr.E","","MHE","IE","MAE","PE"]
    if request.POST:
    	# receive data from template boxes
        u_id = request.POST['u_id']
        u_pass = request.POST['u_pass']
        u_pass_repeat = request.POST['u_pass_repeat']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        u_department = request.POST['u_department']
        u_birth = request.POST['u_birth']
        u_email = request.POST['u_email']
        user_reg = Register.objects.all()
        
        # use sesssions as a cookie to login to other pages
        request.session["userID"] = u_id  # set user ID
        request.session["userPass"] = u_pass  # set user password
        userID = request.session["userID"] # get user ID
       
        # one or more blanket is not allowed
        if(u_id=="" or u_pass=="" or u_pass_repeat=="" or first_name=="" or \
           last_name=="" or u_department=="" or u_birth=="" or \
           u_email=="" or user_reg==""):
            blanks = "YOU HAVE TO FILL IN EVERY BLANKET."
            return render_to_response('user_register.html',locals())
        else :
            for count in user_reg:
                if count.Person_ID == userID:
                    errors = "YOUR ID HAVE ALREADY USED BEFORE."  # your ID have already been used before
                    return render_to_response('login_page.html',locals())
                    
            '''if second password is not like the first
               error = 1 << show insertion password error
            '''
            if(u_pass != u_pass_repeat):
                errors = "YOUR PASSWORD IS DIFFERENT FROM THE LAST ONE."  # insert password again
                return render_to_response('user_register.html',locals())
            else:
                ''' when insertion is correct according to condition of password,
                    create information then store in database
                '''
                Register.objects.create(Person_ID=userID,Password=u_pass,Name=first_name,
                                        SirName=last_name,Birth_date=u_birth,
                                        Department=u_department,Email=u_email)
                # for showing data in template below
                Name = first_name
                SirName = last_name
                set_UserID(userID)
                return render_to_response('login_success.html',locals())
    else:
        ''' at first we begin here
        '''
        return render_to_response('user_register.html',locals())  


def user_forgot_pass(request): # funtion to get template for user is forgot password
     return render_to_response('user_forgot_pass.html',locals())

# change your profile by replace it
@csrf_exempt
def change_profile(request):
    errors=""
    if "userID" in request.session:
        u_id = request.session['userID']
        # use this as choice for department of student or teacher who booked
        depart_list = ["ME","Cpr.E","","MHE","IE","MAE","PE"]
        if request.method == 'POST':         
               u_name = request.POST['first_name']
               u_sur = request.POST['last_name']
               u_depart = request.POST['u_department']
               u_date = request.POST['u_birth']
               u_email = request.POST['u_email']
               
               # one or more blankets is not allowed
               if(u_name=="" or u_sur=="" or u_depart=="" or u_date=="" or u_email==""):
                   errors="PLEASE INSERT ALL BLANKETS."
                   return render_to_response('change_profile.html',locals())
               else:
               	# look for userID then update information of user profile
                   Register.objects.filter(Person_ID = u_id).update(Name = u_name, SirName = u_sur,Birth_date = u_date, Department = u_depart, Email = u_email)
                   return render_to_response('user_profile.html',locals())
        return render_to_response('change_profile.html',locals())
    else:
        return render_to_response('change_profile.html',locals())

@csrf_exempt
def user_get_pass(request): #funtion for User to get password
     u_id = request.POST['u_id']  #user id
     u_email = request.POST['u_email'] #user email
     user_log = Register.objects.all()
     for i in user_log: 
          if(i.Person_ID == u_id and i.Email == u_email):
               state = 1
               break
          elif(i.Person_ID == u_id and i.Email != u_email):
               state = 2
               errors = "Please check your ID and Email again!!!"
          elif(i.Person_ID != u_id):
               state = 3
               errors = "YOUR User ID OR IS NOT VALID."
     user_profile = Register.objects.filter(Person_ID = u_id)
     if state == 1:
          return render_to_response('user_get_pass.html',locals())
     else:
          return render_to_response('user_forgot_pass.html',locals())

# show all profile for each user
def user_profile(request):
	state = 0
	if "userID" in request.session:		
		u_profile = Register.objects.all()
		userID = request.session['userID']
		for i in u_profile:
		# keep all data of Register model to show at template
			if i.Person_ID == userID:
				u_id = i.Person_ID
				u_name = i.Name
				u_sur = i.SirName
				u_date = i.Birth_date
				u_depart = i.Department
				u_email = i.Email
				state = 1
				break
		if state == 1:
		    return render_to_response('user_profile.html',locals())
	        else:
                     return HttpResponseRedirect('/booking/')
	else:
		return HttpResponseRedirect('/')
    
def logout(request):
     if "userID" in request.session: # if uer ID has data
     # delete data then return to http://localhost:8000
	del request.session["userID"]
	return HttpResponseRedirect('/')
     else:
        return HttpResponseRedirect('/')  

def admin_forgot_pass(request): # funtion to get template for user is forgot password
     return render_to_response('admin_forgot_pass.html',locals())

@csrf_exempt
def admin_get_pass(request):
     a_id = request.POST['a_id']
     a_email = request.POST['a_email']
     admin_log = AdminLogin.objects.all()
     for i in admin_log:
          if(i.Admin_ID == a_id and i.Admin_Email == a_email):
               state = 1
               break
          elif(i.Admin_ID == a_id and i.Admin_Email != a_email):
               state = 2
               errors = "Please check your ID and Email again!!!"
               
          elif(i.Admin_ID != a_id):
               state = 3
               errors = "Please check your ID and Email again!!!"
     admin_profile = AdminLogin.objects.filter(Admin_ID = a_id)
     if state == 1:
          return render_to_response('admin_get_pass.html',locals())
     else:
          return render_to_response('admin_forgot_pass.html',locals())

'''
	when user is login through profile site, 
	he can choose to change his password.
'''
@csrf_exempt   
def change_password(request):
    errors = ""  # use for show error to template when errors occur
    state = 0
    # if someone is login to this site
    if "userID" in request.session:
        # there is someone fill information in blankets on template
        if request.POST :
               # receive variable from boxes in template
               o_pass = request.POST['o_pass']
               n_pass = request.POST['n_pass']
               r_n_pass = request.POST['r_n_pass']
             
               # call all Register data model from database 
               u_reg = Register.objects.all()
               
               userID = request.session["userID"]#get user ID
               # forget to insert just a blanket
               if (o_pass=="" or n_pass=="" or r_n_pass==""):
                    errors="PLEASE INSERT ALL BLANKETS"
               else:
                    for i in u_reg:        	
                         # authorize user ID 	
                         if i.Person_ID == userID:
                              # password is correct
                              if i.Password == o_pass:
                                   state = 1
                                   Name = i.Name
                                   SirName = i.SirName
                                   Register.objects.filter(Person_ID = userID).update(Password = n_pass)
                                   break		
                              # password is not authorize
                              elif i.Password != o_pass:
                                   state = 2
                                   errors = "Your password is wrong."
                              if n_pass != r_n_pass:
                                   state = 3
                                   errors = "Repeat your new password."
               # if password is authorize, it goes to next page 
               if state == 1:
                    return render_to_response('login_success.html',locals())
               # if some errors occur, errors wil show up on that page.
               else :
                    return render_to_response('change_password.html',locals())
        else :
               return render_to_response('change_password.html',locals())
    # when someone but user call this function
    else:
        return HttpResponseRedirect('/') 
    

def user_booking(request):
    return render_to_response('user_booking.html')

@csrf_exempt 
def admin_login(request):
    if request.POST:
        errors = ""
        state = 0
        a_id = request.POST['a_id']
        a_pass = request.POST['a_pass']
        admin_log = AdminLogin.objects.all()
        ''' password validated
            if password is not correct send errors
            then show it on web browser
        '''  
        request.session["adminID"] = a_id
        adminID = request.session["adminID"]
        
        for i in admin_log:
            if(i.Admin_ID == adminID and i.Admin_Pass == a_pass):
                state = 1
                break
            elif(i.Admin_ID == adminID and i.Admin_Pass != a_pass):
                state = 2
                errors = "Please check your ID and Password again!!!"
                break
            elif(i.Admin_ID != adminID):
                state = 3
                errors = "Please check your ID and Password again!!!"
        if state == 1:
            return render_to_response('main_admin.html',locals())
        else:
            return render_to_response('admin_login.html',locals())
    else :
        return render_to_response('admin_login.html',locals())

def show_report(request):
    report_list = Computer_Fix.objects.all()
    report_list = Computer_Fix.objects.order_by("Computer_ID")
    return render_to_response('report_computer.html',locals())

@csrf_exempt
def report_user(request):
     if "userID" in request.session:
         errors = ""
         errorsDate  = ""
         count = 0
         report = Computer_Fix.objects.all()
         if request.POST:
             state = 0
             com_id = request.POST['com_id']		
             st_com = request.POST['st_com']
             date_com = request.POST['date_com']	
             if(com_id=="" or st_com =="" or date_com==""):
                   blanks = "YOU HAVE TO FILL IN EVERY BLANKET."
                   return render_to_response('reportErrorByUser.html',locals())
             elif com_id and st_com and date_com :
                if Computer_Fix.objects.filter(Computer_ID = com_id).filter(Date_Error = date_com).count()==0:
                   ''' if input Computer_ID is match with the database and don't report an error on this before '''
                   if Computer_Fix.objects.filter(Computer_ID = com_id) and ComError_History.objects.filter(Error_ID = com_id).filter(Date_Lose = date_com).count() < 1:
                      report = Computer_Fix.objects.filter(Computer_ID = com_id).update(Status_Com = st_com, Date_Error = date_com)
                      state = 1            
                      com_error = ComError_History.objects.create(Error_ID = com_id, Lose = count ,Date_Lose = date_com)
                      com_error = ComError_History.objects.filter(Error_ID = com_id)
                      if ComError_History.objects.filter(Error_ID = com_id).count()==1:
                         com_error = ComError_History.objects.filter(Error_ID = com_id).update(Lose = 1)
                      elif ComError_History.objects.filter(Error_ID = com_id).count() > 1: 
                         for i in com_error :	
                             count = count + 1             
                         com_error = ComError_History.objects.filter(Error_ID = com_id).update(Lose = count)
                      com_error = ComError_History.objects.all()
                   elif Computer_Fix.objects.filter(Computer_ID = com_id).count()==0:    #id doesn't contain in object
                      errors = "COMPUTER NUMBER INCORRECT"  # your ID have already been used before
                      state = 2
                   elif ComError_History.objects.filter(Error_ID = com_id).filter(Date_Lose = date_com).count() > 0:
                      errorsDate  = "DATE ERROR INCORRECT"  # your date have already been used before
                      state = 3
                elif ComError_History.objects.filter(Error_ID = com_id).filter(Date_Lose = date_com).count() > 0:
                   errorsDate  = "DATE ERROR INCORRECT"  # your date have already been used before
                   state = 3
                if state == 1:
                   return render_to_response('report_success.html',locals())

                else:
                   return render_to_response('reportErrorByUser.html',locals())
         else :
             return render_to_response('reportErrorByUser.html',locals())
          

@csrf_exempt
def modify_report_fromAdmin(request):
    errors = ""
    report_list = Computer_Fix.objects.all()
    if request.POST:
        
        state = 0
        com_id = request.POST['com_id']		
        st_com = request.POST['st_com']
        #date_com = request.POST['date_com']	
        report_list = Computer_Fix.objects.all()
        
        if(com_id=="" or st_com =="" ):
           blanks = "YOU HAVE TO FILL IN EVERY BLANKET."
           return render_to_response('modifyReport.html',locals())

        elif Computer_Fix.objects.filter(Computer_ID = com_id):
           report_list = Computer_Fix.objects.filter(Computer_ID = com_id).update(Status_Com = st_com)
           state = 1
           return render_to_response('modify_success.html',locals())

        elif Computer_Fix.objects.filter(Computer_ID = com_id).count()==0: #id doesn't contain in object
           state = 2
           errors = "COMPUTER NUMBER INCORRECT"  # your ID have already been used before
           return render_to_response('modifyReport.html',locals())
    else :
        return render_to_response('modifyReport.html',locals())

class ScaleCountError:    
    def add(self,data, y_pos ,count_error,temp_minus):
        for i in range(1,11) :
            data[i] = []
            data[i].append(count_error)
            data[i].append(y_pos)            
            count_error = count_error - temp_minus
            y_pos = y_pos + 40
        return data 

class Position_Histogram:
    def __init__(self):
        self.X_Pos= 0
        self.Y_Pos= 0
        self.Height= 0    
    def setX_Pos(self,x):
        self.X_Pos = x
    def setY_Pos(self,y):
        self.Y_Pos = y    
    def setHeight(self,h):
        self.Height = h

def draw_histogramError(request):
    count_error_list = []		#list of objects ComError_History
    height_y = []			#height list of each bar
    scale_lineY = []
    temp_y = 460
    scale_lineX = []
    temp_x = 240
    tempp=0
    max_error = 0   
    temp_text = 236
    scale_text = []
    scale_numError = []    
    y_pos_temp = 0
    temp_xx = 220
    temp_yy = 0
    temp_height = 0
    his = []
    x_line = 850
    x_line_comID = 860 
    com_num = Computer_Fix.objects.all()
    len_comNum = len(com_num)
    len_com = len(com_num)
   
    for i in com_num:	
        count_error_list.append(len(ComError_History.objects.filter(Error_ID=i.Computer_ID)))

    max_error = max(count_error_list)
    #Calculate height
    for j in count_error_list:	
        tempp =  (j*400)/max_error 	
        height_y.append( tempp )

    #Calculate scale y
    for count_scaleY in range(1,11):
        scale_lineY.append(temp_y)	
        temp_y = temp_y - 40


    #Calculate scale x
    for count_scaleX in com_num:
        scale_lineX.append(temp_x)	
        temp_x = temp_x + 60 
        
    #Calculate scale number text
    his_text = []  
    #numText = 1  
    for count_text in com_num:
        histogram_text = Position_Histogram()
        histogram_text.setX_Pos(temp_text)       
        histogram_text.setY_Pos(525)
        histogram_text.setHeight(count_text.Computer_ID)
        his_text.append(histogram_text)
        temp_text = temp_text+60 
        #numText = numText + 1
  
    
    #Calculate scale histogram   
    for count_height in height_y:
        temp_yy = 500 - count_height       
        temp_height = count_height
        histogram = Position_Histogram()
        histogram.setX_Pos(temp_xx)
        histogram.setY_Pos(temp_yy)   
        histogram.setHeight(temp_height)
        his.append(histogram)
        temp_xx = temp_xx+60 
            
    lenH = len(his)

    #Calculate scale num error
    temp_yNum = 105
    temp_numError = max_error
    temp_minus = int(max_error/10)
    data = {}
    numError = ScaleCountError()
    scaleEror_ob = numError.add(data, temp_yNum ,temp_numError,temp_minus).values()

     
    if len_com > 10 :
       len_com = len_com -10
       for i in range(0,len_com):   
           x_line = x_line+80
           x_line_comID = x_line_comID + 80

    return render_to_response('histogram.html',locals())

def draw_hisComUse(request):
    scale_lineY = []
    temp_y = 460
    scale_lineX = []
    temp_x = 240
    temp_text = 236
    scale_text = []
    height_y = []
    count_reserved = Computer.objects.all()
    reserved_list =  []	
    temp_reserved = 0
    max_reserved = 0
    temp_com = Computer.objects.all()
    com_num = [] 
    for count in temp_com:
        com_num.append(count.Computer_ID)
    
    len_com = len(com_num)
    for i in count_reserved:
        temp_reserved = i.Frequency
        reserved_list.append(temp_reserved)
    max_reserved = max(reserved_list)
    
    tempp=0
    temp_xx = 220
    temp_yy = 0
    #Calculate height
    for j in reserved_list :	
        tempp =  (j*400)/max_reserved  	
        height_y.append( tempp )

    #Calculate scale y
    for count_scaleY in range(1,11):
        scale_lineY.append(temp_y)	
        temp_y = temp_y - 40


    #Calculate scale x
    for count_scaleX in com_num:
        scale_lineX.append(temp_x)	
        temp_x = temp_x + 60 

    #Calculate scale number text
    his_text = []  
    for count_text in com_num:
        histogram_text = Position_Histogram()
        histogram_text.setX_Pos(temp_text)       
        histogram_text.setY_Pos(525)
        histogram_text.setHeight(count_text)
        his_text.append(histogram_text)
        temp_text = temp_text+60 

    #Calculate scale histogram
    his = []
    for count_height in height_y:
        temp_yy = 500 - count_height       
        temp_height = count_height
        histogram = Position_Histogram()
        histogram.setX_Pos(temp_xx)
       
        histogram.setY_Pos(temp_yy)
     
        histogram.setHeight(temp_height)
        his.append(histogram)
        temp_xx = temp_xx+60 

    #Calculate scale num error
    temp_yNum = 105
    temp_numError = max_reserved
    temp_minus = int(max_reserved/10)
    data = {}
    numReserved = ScaleCountError()

    scaleReserved_ob = numReserved.add(data, temp_yNum ,temp_numError,temp_minus).values()
    x_line = 850
    x_line_comID = 860
    
    #Calculate if add computer id more than 10 , add axis x
    if len_com > 10 :
       len_com = len_com -10
       for i in range(0,len_com):   
           x_line = x_line+80
           x_line_comID = x_line_comID + 80
   
    return render_to_response('histogramComUse.html',locals())
